﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using AzureGames.Model;
using System.Collections.Specialized;

using AzureGames.Data.Implementation.ServiceEntities;

namespace AzureGames.Data.Implementation
{
    internal class BoardPlayerRepository : AzureTableRepository<BoardPlayerEntity>
    {
        const string PARTITIONKEY = "BoardPlayer";

        public BoardPlayerRepository() : base("BoardPlayer") { }

        public List<string> GetBoardPlayers(Guid boardID)
        {
            // TODO: figure out why this can not be done in one step
            //return dataContext.CreateQuery<GamePlayerEntity>(this.tableName)
            //    .Where(n=> n.PartitionKey==PARTITIONKEY && n.GameID==gameID)
            //    .OrderBy(n=>n.PlayerOrder)
            //    .Select(n=>n.PlayerValue)
            //    .ToList();

            var entities = dataContext.CreateQuery<BoardPlayerEntity>(this.tableName)
                .Where(n => n.PartitionKey == PARTITIONKEY && n.BoardID == boardID);

            var l = entities.ToList();

            return l.OrderBy(n => n.PlayerOrder).Select(n => n.PlayerID)
                    .ToList();
        }

        public BoardPlayerEntity GetBoardPlayer(Guid boardID, int order)
        {
            var player = dataContext.CreateQuery<BoardPlayerEntity>(this.tableName)
                .Where(n => n.PartitionKey == PARTITIONKEY && n.BoardID == boardID && n.PlayerOrder == order)
                .FirstOrDefault();
                
            if(player==null)
                return null;
            else
                return player;
        }

        public AzureResult AddBoardPlayer(BoardPlayerEntity resource)
        {
            Add(resource);

            return new AzureResult { Code = 0 };
        }

        public AzureResult UpdatBoardPlayer(BoardPlayerEntity resource)
        {
            resource.LastUpdatedDate = DateTime.Now;
            Update(resource);

            return new AzureResult { Code = 0 };
        }
        
      

    }
}
